package com.atguigu.controller;

import com.atguigu.domain.User;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * UserController
 *
 * @Author: 马伟奇
 * @CreateTime: 2021-03-03
 * @Description:
 */
@RestController
@DefaultProperties(defaultFallback="failBack") // 全局熔断器
@RequestMapping("/consumer")
public class UserController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    /**
     * 全局熔断器，需要去掉参数，因为有些熔断器有参数，有些没有
     * @return
     */
    public User failBack(){
        User user = new User();
        user.setUsername("我已经宕机了,服务降级，请不要在请求我...");
        return user;
    }

    @RequestMapping("/{id}")
    @HystrixCommand
    public User queryById(@PathVariable(value = "id")Integer id){
//        String url = "http://localhost:18081/user/find/"+id;

//        // 参数表示服务的唯一标识符
//        // 应用程序的名称是唯一
//        List<ServiceInstance> lists = discoveryClient.getInstances("user-provider");
//
//        ServiceInstance serviceInstance = lists.get(0);
//        // 拼接URL地址
//        String url = "http://"+serviceInstance.getHost() +":" + serviceInstance.getPort()+"/user/find/"+id;
        String url = "http://user-provider/user/find/"+id;
        User user = restTemplate.getForObject(url, User.class);
        return user;
    }
}